package kuzha.runtime.jadapter;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.script.Bindings;

import kuzha.KuzhaObject;
import kuzha.runtime.Converter;

public class ToBindingsAdapter extends AbstractMap<String, Object> implements Bindings {
	private final Map<String, KuzhaObject> table;
	
	public ToBindingsAdapter(Map<String, KuzhaObject> table) {
		if (table == null)
			throw new IllegalArgumentException();
		this.table = table;
	}
	
	@Override
	public Set<Map.Entry<String, Object>> entrySet() {
		return new AbstractSet<Map.Entry<String, Object>>() {
			public Iterator<Map.Entry<String, Object>> iterator() {
				final Iterator<Map.Entry<String, KuzhaObject>> iter = table.entrySet().iterator();
				return new Iterator<Map.Entry<String, Object>>(){
					@Override
					public boolean hasNext() {
						return iter.hasNext();
					}
					@Override
					public Map.Entry<String, Object> next() {
						Map.Entry<String, KuzhaObject> ent = iter.next();
						return new AbstractMap.SimpleImmutableEntry<String, Object>(
								ent.getKey(),
								Converter.toJavaObject(ent.getValue())
							);
					}
					@Override
					public void remove() {
						iter.remove();
					}
				};
			}
			public int size() {
				return ToBindingsAdapter.this.table.size();
			}
		};
	}
	
	@Override
	public Object put(String key, Object value) {
		return Converter.toJavaObject(table.put(key, Converter.toKuzhaObject(value)));
	}
}
